package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"log"
	"net"
	"os"
	"strings"
	"unsafe"
)

/*
*
客户端与服务器的消息传递格式
*/
type ClientMsg struct {
	To      string  `json:"to"`
	MsgType int     `json:"msgtype"`
	Msg     string  `json:"msg"`
	Datalen uintptr `json:"datalen"`
}

const (
	LOGIN = iota
	LOGOUT
	SETNAME
	BROADCAST
	PRIVATE
)

func Help() {
	fmt.Println("1. set: your name")
	fmt.Println("2. all: your msg")
	fmt.Println("1. anyone: your msg")
}

/**
处理连接
*/

func handle_conn(conn net.Conn) {
	buf := make([]byte, 256)
	for {
		n, err := conn.Read(buf)
		if err != nil || n <= 0 {
			log.Panic("Failed to read", err)
		}
		fmt.Println(string(buf[:n]))
		fmt.Println("pdj's chat>")
	}
}

/*
*
客户端获得链接，一个线程持有链接去读取服务器输入，一个线程持有链接去获取客户端输入，向服务器发送数据
*/
func main() {
	Help()
	conn, err := net.Dial("tcp", "localhost:8080")
	if err != nil {
		log.Panic("Failed to Dial ", err)
	}
	defer conn.Close()

	go handle_conn(conn)
	fmt.Println("Welcome to pdj's chat")

	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Printf("pdj's chat >")
		msg, err := reader.ReadString('\n')
		if err != nil {
			log.Panic("Failed to readString ", err)
		}
		msg = strings.Trim(msg, "\r\n")
		if msg == "quit" {
			fmt.Println("Bye Bye")
			break
		}
		msgs := strings.Split(msg, ":")
		if len(msgs) == 2 {
			msgtype := PRIVATE
			switch msgs[0] {
			case "set":
				msgtype = SETNAME
			case "all":
				msgtype = BROADCAST

			}
			var climsg ClientMsg
			climsg.MsgType = msgtype
			climsg.To = msgs[0]
			climsg.Msg = msgs[1]
			climsg.Datalen = unsafe.Sizeof(climsg)
			data, _ := json.Marshal(climsg)
			conn.Write(data)
		}
	}

}
